package objectManager;

import java.util.*;
import objectManager.CBaseObject;

/*****************************
*  THIS IS A SINGLETON CLASS
******************************/

public class CObjectManager 
{
	/***********************
	* Member Variables.
	************************/
	// Vector to store the base objects in.
	Vector<CBaseObject> objects = new Vector<CBaseObject> (0, 1);
	
	// Default Constructor
	private CObjectManager ()
	{
	}
	
	// The keyword 'synchronized' is used to prevent two threads from entering 
	// 'getObjectManager ()' at the same time. This will ensure that our 
	// singleton is thread safe. 
	public static synchronized CObjectManager getObjectManager ()
	{
		if (instance == null)
		{
			// Creating the one and only instance of CObjectManager
			instance = new CObjectManager ();
		}
		return instance;
	}
	private static CObjectManager instance;
		
	// If the CObjectManager class was to extend from a class that supports
	// cloning, another instance of CObjectManager could be created. So to 
	// prevent this, the 'clone ()' method is overwritten to throw an exception.
	// This ensures that 'CObjectManager' truly is a singleton.
	public Object clone()
		throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException(); 
	}
	
	/***********************
	* Class Methods.
	************************/
	public void UpdateObjects (float time)
	{
		// Create an iterator to move through our list.
		Iterator<CBaseObject> iter = objects.iterator();
		// make sure we're not at the end of the list before we continue.
		while (iter.hasNext())
		{
			// call each objects 'Updtate ()' method from their super class.
			iter.next().Update(time);
		}
	}
	
	public void RenderObjects ()
	{	
		// Create an iterator to move through our list.
		Iterator<CBaseObject> iter = objects.iterator();
		// make sure we're not at the end of the list before we continue.
		while (iter.hasNext())
		{
			// call each objects 'Render ()' method from their super class.
			iter.next().Render();
		}
	}
	
	public void AddObject (CBaseObject object)
	{	
		// Sanity check.
		if (object == null)
			return;
		
		// add the object to the end of the object list
		objects.add(object);
	}
	
	public void RemoveObject (CBaseObject object)
	{
		// Sanity check.
		if (object == null)
			return;
		
		// Create an iterator to move through our list.
		Iterator<CBaseObject> iter = objects.iterator();
		// make sure we're not at the end of the list before we continue.
		while (iter.hasNext())
		{
			// Locate the passed in object inside of our object list and remove it.
			if (iter.next().equals(object))
				iter.remove();
		}
	}
	
	public void RemoveAllObjects ()
	{
		// Clear all elements from the list.
		if (objects.isEmpty() == false)
			objects.clear();
	}

	public Vector<CBaseObject> getList() 
	{
		return objects;
	}
}
